package com.hgb.mall.admin.services.impl;

import com.github.pagehelper.PageHelper;
import com.hgb.mall.admin.services.SmsHomeNewProductService;
import com.hgb.mall.mbg.entity.SmsHomeNewProduct;
import com.hgb.mall.mbg.mapper.SmsHomeNewProductDynamicSqlSupport;
import com.hgb.mall.mbg.mapper.SmsHomeNewProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static org.mybatis.dynamic.sql.SqlBuilder.*;

/**
 * 首页新品推荐管理Service实现类
 * Created by hgb on 2020/11/6.
 */
@Service
public class SmsHomeNewProductServiceImpl implements SmsHomeNewProductService {
    @Autowired
    private SmsHomeNewProductMapper homeNewProductMapper;

    @Override
    public int create(List<SmsHomeNewProduct> homeNewProductList) {
        for (SmsHomeNewProduct SmsHomeNewProduct : homeNewProductList) {
            SmsHomeNewProduct.setRecommendStatus(1);
            SmsHomeNewProduct.setSort(0);
            homeNewProductMapper.insert(SmsHomeNewProduct);
        }
        return homeNewProductList.size();
    }

    @Override
    public int updateSort(Long id, Integer sort) {
        SmsHomeNewProduct homeNewProduct = new SmsHomeNewProduct();
        homeNewProduct.setId(id);
        homeNewProduct.setSort(sort);
        return homeNewProductMapper.updateByPrimaryKeySelective(homeNewProduct);
    }

    @Override
    public int delete(List<Long> ids) {
        return homeNewProductMapper.delete(c -> c.where(SmsHomeNewProductDynamicSqlSupport.id, isIn(ids)));
    }

    @Override
    public int updateRecommendStatus(List<Long> ids, Integer recommendStatus) {

        return homeNewProductMapper.update(r -> r
                .set(SmsHomeNewProductDynamicSqlSupport.recommendStatus).equalTo(recommendStatus)
                .where(SmsHomeNewProductDynamicSqlSupport.id, isIn(ids)));
    }

    @Override
    public List<SmsHomeNewProduct> list(String productName, Integer recommendStatus, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        return homeNewProductMapper.select(c -> c
                .where(SmsHomeNewProductDynamicSqlSupport.productName, isLikeWhenPresent(productName)
                        .then(s -> "%" + s + "%"))
                .and(SmsHomeNewProductDynamicSqlSupport.recommendStatus, isEqualToWhenPresent(recommendStatus))
                .orderBy(SmsHomeNewProductDynamicSqlSupport.sort.descending())

        );
    }
}
